package com.azt.back.action.quartz;

import com.azt.api.pojo.quartz.ScheduleJob;
import com.azt.api.service.quartz.TimeTaskService;
import com.azt.back.util.SpringContextUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;


/**
 * 
 * @author 张栋 2016年4月6日上午9:28:34
 */
public class LoadTask{
	private Logger  log  = LoggerFactory.getLogger("myQuartz");

	@Autowired
	private TimeTaskService titmeTaskService;

	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;

	public void init() {
		start(null);
	}

	public boolean start(Integer scheID) {

		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		List<ScheduleJob> jobList = null;
		if (scheID != null) {

			jobList = new ArrayList<ScheduleJob>();
			ScheduleJob sJob = titmeTaskService.getScheduleJobById(scheID);

			jobList.add(sJob);

		} else {
			jobList = titmeTaskService.getAllStarted();
		}
		if (jobList == null)
			return false;

		try {
			for (ScheduleJob job : jobList) {
			    System.out.println("定时任务启动:"+job.getJob_name());
				TriggerKey triggerKey = TriggerKey.triggerKey(job.getJob_name(), Scheduler.DEFAULT_GROUP);

				// 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
				CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
				// 不存在，创建一个
				if (null == trigger) {
					JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(job.getJob_name(), Scheduler.DEFAULT_GROUP).build();
					jobDetail.getJobDataMap().put("scheduleJob", job);
					// 表达式调度构建器
					CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCron_expression());
					// 按新的cronExpression表达式构建一个新的trigger
					trigger = TriggerBuilder.newTrigger().withIdentity(job.getJob_name(), Scheduler.DEFAULT_GROUP).withSchedule(scheduleBuilder).build();
					scheduler.scheduleJob(jobDetail, trigger);
				} else {
					// Trigger已存在，那么更新相应的定时设置
					// 表达式调度构建器
					CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCron_expression());
					// 按新的cronExpression表达式重新构建trigger
					trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
					// 按新的trigger重新设置job执行
					scheduler.rescheduleJob(triggerKey, trigger);
				}

				//
				int jobStatus = job.getJob_status();
				if (jobStatus == 0) {
					job.setJob_status(1);
					titmeTaskService.updateEntitie(job);
				}
			}

			return true;
		} catch (SchedulerException e) {
			log.error("定时任务启动异常");
			e.printStackTrace();
			return false;
		}
	}

	public boolean stop(Integer scheID) {
		ScheduleJob sJob = titmeTaskService.getScheduleJobById(scheID);
		try {
			pauseJob(sJob);
			sJob.setJob_status(0);
			titmeTaskService.updateEntitie(sJob);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;

	}

	public boolean delete(Integer scheID) {
		ScheduleJob sJob = titmeTaskService.getScheduleJobById(scheID);
		try {
			deleteJob(sJob);
			titmeTaskService.delScheduleJob(sJob);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean update(Integer scheID) {
		ScheduleJob sJob = titmeTaskService.getScheduleJobById(scheID);
		try {
			updateJobCron(sJob);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public boolean runAJobNow(Integer scheID){
		ScheduleJob sJob = titmeTaskService.getScheduleJobById(scheID);
		try {
			runAJobNow(sJob);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	/**
	 * 暂停一个job
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void pauseJob(ScheduleJob scheduleJob) throws SchedulerException {
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobKey jobKey = JobKey.jobKey(scheduleJob.getJob_name(), Scheduler.DEFAULT_GROUP);
		scheduler.pauseJob(jobKey);
	}

	/**
	 * 恢复一个job
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void resumeJob(ScheduleJob scheduleJob) throws SchedulerException {
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobKey jobKey = JobKey.jobKey(scheduleJob.getJob_name(), Scheduler.DEFAULT_GROUP);
		scheduler.resumeJob(jobKey);
	}

	/**
	 * 删除一个job
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void deleteJob(ScheduleJob scheduleJob) throws SchedulerException {
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobKey jobKey = JobKey.jobKey(scheduleJob.getJob_name(), Scheduler.DEFAULT_GROUP);
		scheduler.deleteJob(jobKey);

	}

	/**
	 * 立即执行job
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void runAJobNow(ScheduleJob scheduleJob) throws SchedulerException {
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobKey jobKey = JobKey.jobKey(scheduleJob.getJob_name(), Scheduler.DEFAULT_GROUP);
		//可能不存在
		JobDetail jobDetail = scheduler.getJobDetail(jobKey);
		//判断job是否存在
		if(jobDetail!=null){
			scheduler.triggerJob(jobKey);
		}else{
			TaskInterface bean = (TaskInterface) SpringContextUtil.getBean(scheduleJob.getJob_name());
			bean.execute();
		}
	}

	/**
	 * 更新job时间表达式
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void updateJobCron(ScheduleJob scheduleJob) throws SchedulerException {
		Scheduler scheduler = schedulerFactoryBean.getScheduler();

		TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJob_name(), Scheduler.DEFAULT_GROUP);

		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCron_expression());

		trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

		scheduler.rescheduleJob(triggerKey, trigger);
	}

}
